import React, { Suspense, useEffect } from 'react';
import {
  Routes,
  Route,
  useNavigate,
  useLocation,
  useParams,
  useSearchParams,
  Link,
} from 'react-router-dom';
import routes from './routes';

const Loading = () => {
  return <div className="loading">Loading...</div>;
};

//
const Element = (props) => {
  let { component: Component, meta, path } = props;

  // 修改title
  document.title = meta.title;

  // 获取路由信息，统一配置，路由页面不需要再单独引入理由文件
  const navigate = useNavigate();
  const location = useLocation();
  const params = useParams();
  const [usp] = useSearchParams();

  // 根据业务做相关的操作
  // todo

  return (
    <Component
      navigate={navigate}
      location={location}
      params={params}
      usp={usp}
      Link={Link}
    />
  );
};

export default function RouterView() {
  return (
    <Suspense fallback={<Loading />}>
      <Routes>
        {routes.map((item) => {
          const { name, path } = item;
          return (
            /* Element不能返回Promise实例 */
            <Route key={name} path={path} element={<Element {...item} />} />
          );
        })}
      </Routes>
    </Suspense>
  );
}
